package com.yupi.yupicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

/**
 * 通过url上传图片
 *
 */
@Service
@Slf4j
public class UrlPictureUpload extends PictureUploadTemplate {
    @Override
    protected void processFile(Object inputSource, File file) throws Exception {
        String fileUrl = (String) inputSource;
        HttpUtil.downloadFile(fileUrl, file);
    }

    @Override
    protected String getOrginalFilename(Object inputSource) {
        String fileUrl = (String) inputSource;
        return FileUtil.mainName(fileUrl);
    }

    @Override
    protected void validPicture(Object inputSource) {
        String fileUrl = (String) inputSource;
        //校验非空
        ThrowUtils.throwIf( StringUtils.isBlank(fileUrl), ErrorCode.PARAMS_ERROR,"文件地址为空");
        //校验URL格式
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR,"文件地址格式错误");
        }
        //校验URL协议
        // 只允许http和https
        ThrowUtils.throwIf(!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://"), ErrorCode.PARAMS_ERROR,"文件地址协议错误");
        //发送HEAD 请求文件是否存在
        HttpResponse execute = null;
        try {
            execute = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
            if (execute.getStatus() != HttpStatus.SC_OK) {
                log.error("文件地址不存在");
                return;
            }
            //文件存在，校验文件后缀
            String contentType = execute.header("Content-Type");
            if (contentType != null) {
                String suffix = FileUtil.getSuffix(contentType);
                final List<String> fileSuffixList = Arrays.asList("image/jpg", "image/jpeg", "image/png", "image/webp");
                ThrowUtils.throwIf(!fileSuffixList.contains(contentType.toLowerCase()), ErrorCode.PARAMS_ERROR,"上传图片格式不正确");
            }
            //文件存在，校验文件大小
            String contentSize = execute.header("Content-Length");
            if (contentSize != null){
                try {
                    ThrowUtils.throwIf(Long.parseLong(contentSize) > 1024 * 1024 * 2, ErrorCode.PARAMS_ERROR,"上传图片不能大于2M");
                }catch (NumberFormatException e){
                    throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件大小格式异常");
                }
            }
        }finally {
            if (execute != null) {
                execute.close();
            }
        }
    }
}
